package com.zyl.file.service.impl;

import cn.hutool.core.util.ObjectUtil;

import com.zyl.file.service.CacheCommonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.dromara.sms4j.starter.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 缓存公共方法
 *
 * @author PJW
 */
@Slf4j
@Service
public class CacheCommonServiceImpl implements CacheCommonService {


    public final static java.util.List<String> VIDEOS = Collections.unmodifiableList(Arrays.asList("wmv", "asf", "rm", "rmvb", "avi", "mov", "mpg", "flv"));
    public final static java.util.List<String> IMGS = Collections.unmodifiableList(Arrays.asList("gif", "jpg", "jpeg", "png", "psd", "bmp", "wbmp", "pnm", "jpe", "webp", "heif", "heic"));
    public final static java.util.List<String> SPECIALIMGS = Collections.unmodifiableList(Arrays.asList("psd", "bmp", "wbmp", "pnm", "jpe", "webp", "heif", "heic"));
    public final static java.util.List<String> DOCS = Collections.unmodifiableList(Arrays.asList("txt", "doc", "wps", "docx", "xls", "ppt", "pptx", "xlsx", "ini"));
    public final static java.util.List<String> TIFANDOFD = Collections.unmodifiableList(Arrays.asList("ofd", "heif"));
    public static final java.util.List<String> TIFFLIST = Collections.unmodifiableList(Arrays.asList("tiff", "tif"));
    public final static java.util.List<String> AUDIOS = Collections.unmodifiableList(Arrays.asList("amr", "ogg", "m4a"));
    public final static java.util.List<String> PDF = Collections.unmodifiableList(Arrays.asList("pdf"));
    public final static java.util.List<String> DOCX = Collections.unmodifiableList(Arrays.asList("docx"));
    public final static List<String> XLS = Collections.unmodifiableList(Arrays.asList(new String[]{"xls", "xlsx"}));

    /**
     * 文件加水印线程池
     */
    public static final ExecutorService EXECUTOR = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "MyThreadPool-" + threadNumber.getAndIncrement());
            }
        });
    @Value("${upload.temp-dir}")
    private String sftpDirectory;

    @Override
    public InputStream getFileCache(String fileName, String ext) {
        // 获取文件缓存绝对路径
        String filePath = getFileCachePath(fileName, ext);
        // 其他格式的不需要缓存，直接返回文件
        if (ObjectUtil.isEmpty(filePath)) {
            // 是否缓存
            return null;
        }
        // 获取存储服务服务器ip
        InputStream fileInputStream = null;

        // 缓存服务与存储服务服务器在同一台服务器，获取文件路径
        long start = System.currentTimeMillis();
        // 获取本地缓存文件
        File file0 = new File(filePath);
        if (file0.exists()) {
            // 文件存在
            try {
                fileInputStream = new FileInputStream(file0);
            } catch (IOException e) {
                log.info("获取文件byte错误", e);
                throw new RuntimeException(e);
            }
        }
        long end = System.currentTimeMillis();
        log.info("缓存服务器与存储服务服务器在同一服务器：获取缓存文件耗时：{}(毫秒)", end - start);
        return fileInputStream;
    }

    @Override
    public void cacheFile(InputStream inputStream, String url, Long fileId, String fileExt, Integer isEncrypt,
        String encryptKey, String encryptIndex) {
        String newExt = getNewExt(fileExt);
        if (ObjectUtil.isEmpty(inputStream)) {
            log.error("缓存文件方法的文件流入参为空");
        }
        try {
            log.info("重新缓存文件2");
//            SunCacheUtils.cacheFile(inputStream, url, sftpDirectory, fileId, newExt, fileExt, isEncrypt, encryptKey,
//                encryptIndex);
        } catch (Exception e) {
            log.error(e.toString());
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取文件缓存绝对路径
     *
     * @param fileName 文件id
     * @param ext 文件后缀
     * @return Result
     */
    private String getFileCachePath(String fileName, String ext) {
        String newExt = getNewExt(ext);
        if (newExt == null) {
            return null;
        }
        return sftpDirectory + fileName + "." + newExt;
    }

    /**
     * 后缀转换
     *
     * @param ext 原后缀
     * @return String
     */
    private String getNewExt(String ext) {
        String newExt = ext;
        if (VIDEOS.contains(ext.toLowerCase())) {
            newExt = "mp4";
        } else if (IMGS.contains(ext.toLowerCase())
            && !TIFFLIST.contains(ext.toLowerCase())) {
            // 图片生成缩略图处理
            newExt = "png";
        } else if (DOCS.contains(ext.toLowerCase()) || TIFANDOFD.contains(ext.toLowerCase())
            || TIFFLIST.contains(ext.toLowerCase()) || PDF.contains(ext.toLowerCase())) {
            // 文档转换pdf处理
            newExt = "pdf";
        } else if (AUDIOS.contains(ext.toLowerCase())) {
            newExt = "mp3";
        } else {
            return null;
        }
        return newExt;
    }


}
